package com.tange.ai.iot.client.gnssa.message

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityMessageSettingBinding
import com.tange.base.toolkit.*
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.core.cloud.message.CloudMessage
import com.tange.core.cloud.message.LocalPushConfigure
import com.tange.core.cloud.message.RemotePushConfigure
import com.tange.core.cloud.message.PushSwitch

class MessageSettingActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MessageActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, MessageSettingActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var binding: ActivityMessageSettingBinding
    private lateinit var listAdapter: ListAdapter
    private lateinit var deviceId: String
    private var loading: BasicDialogLoading? = null

    private var remoteSetting: RemotePushConfigure? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!

        binding = ActivityMessageSettingBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
        }

        binding.top.left.onClicked { finish() }

        listAdapter = ListAdapter()
        binding.msgList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.msgList.adapter = listAdapter

        loading = BasicDialogLoading(this).apply {
            setMessage("刷新中...")
        }
        loading?.dismiss()
        loading?.show()

        binding.globalSwitch.onClicked {
            remoteSetting?.let {

                val categoryNeedToPush = ArrayList<String>()
                it.switcher?.forEach { if (it.enable == true) categoryNeedToPush.add(it.categoryLabel ?: "") }
                if (categoryNeedToPush.isEmpty()){
                    //全局开关，必须要有一个类别开启，否则不允许开启
                    categoryNeedToPush.add("body")
                }
                val configure = LocalPushConfigure(it.enable, it.interval, it.undisturbed, categoryNeedToPush)
                val newState = !(it.enable == true)
                configure.enable = newState

                update(configure)
            }
        }

        query()
    }

    private fun update(configure: LocalPushConfigure) {
        loading?.dismiss()
        loading?.show()

        CloudMessage.updatePushingSwitch(deviceId, configure) {
            if (it.success) {
                Tips.show("更新成功")
                query()
            }
            else {
                loading?.dismiss()
                Tips.show("更新失败：${it.code}, ${it.message}")
            }
        }
    }

    private fun query() {
        CloudMessage.queryPushingSwitch(deviceId) {
            loading?.dismiss()
            if (it.success) {
                it.data?.let { refresh(it) }
            } else {
                Tips.show("请求失败：${it.code}, ${it.message}")
            }
        }
    }

    private fun refresh(setting: RemotePushConfigure) {
        binding.globalLayout.visible()

        remoteSetting = setting

        val categoryNeedToPush = ArrayList<String>()
        setting.switcher?.forEach {
            if (it.enable == true) categoryNeedToPush.add(it.categoryName ?: "")
        }

        if (setting.enable == true) {
            binding.globalSwitch.setImageDrawable(
                ContextCompat.getDrawable(
                    this@MessageSettingActivity,
                    com.tange.base.ui.design.featured.R.drawable.basic_checked_button_style_switch_on
                )
            )
            binding.childSwitch.visible()
        } else {
            binding.globalSwitch.setImageDrawable(
                ContextCompat.getDrawable(
                    this@MessageSettingActivity,
                    com.tange.base.ui.design.featured.R.drawable.basic_checked_button_style_switch_off
                )
            )
            binding.childSwitch.gone()
        }

        setting.switcher?.let {
            listAdapter.refresh(it)
        }
    }

    inner class ListAdapter : RecyclerView.Adapter<ViewHolder>() {
        private val switches: MutableList<PushSwitch> = java.util.ArrayList()

        fun refresh(list: List<PushSwitch>) {
            switches.clear()
            switches.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
            val view: View = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.item_message_switch, viewGroup, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
            val item = switches[position]
            viewHolder.name.text = item?.categoryName ?: ""

            val enabled = item.enable == true
            if (enabled) {
                viewHolder.enable.setImageDrawable(ContextCompat.getDrawable(this@MessageSettingActivity,
                    com.tange.base.ui.design.featured.R.drawable.basic_checked_button_style_switch_on
                ))
            } else {
                viewHolder.enable.setImageDrawable(ContextCompat.getDrawable(this@MessageSettingActivity,
                    com.tange.base.ui.design.featured.R.drawable.basic_checked_button_style_switch_off
                ))
            }

            viewHolder.itemView.setOnClickListener {
                val newState = !enabled
                item.enable = newState

                remoteSetting?.let {

                    val categoryNeedToPush = ArrayList<String>()
                    it.switcher?.forEach { if (it.enable == true) categoryNeedToPush.add(it.categoryLabel ?: "") }
                    val configure = LocalPushConfigure(it.enable, it.interval, it.undisturbed, categoryNeedToPush)
                    update(configure)
                }
            }
        }

        override fun getItemCount(): Int {
            return switches.size
        }
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val enable: ImageView
        val name: TextView

        init {
            enable = view.findViewById(R.id.enable)
            name = view.findViewById(R.id.name)
        }
    }
}